from collections import OrderedDict

from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


class CustomPagination(PageNumberPagination):
    page_size = 9999
    page_query_param = 'page'
    page_size_query_param = 'page_size'
    max_page_size = 20

    def __init__(self):
        self.total = 0

    def paginate_queryset(self, queryset, request, view=None):
        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = self.get_page_number(request, paginator)
        self.total = len(queryset)
        #
        # if (total // page_size) == 0:
        #     page_number = 1
        # else:
        #     page_number = (total // page_size) if int(page_number) > (total // page_size) + 1 else page_number

        try:
            self.page = paginator.page(page_number)
        except InvalidPage as exc:
            return []

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request
        return list(self.page)

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('total', self.total),
            ('code', 200),
            ('message', 'ok'),
            ('data', data),
        ]))
